<template>
	<eui-page-frame topHeight="170" bottomHeight="124">
		<template #top>
			<view class="navigation">
				<eui-nav-bar :title="title" color="#000000" rightIcon="" />
			</view>
		</template>
		<eui-page-content>
			<eui-base-card title="申请信息">
				<eui-card-input v-model="dataModel.c_store_name" title="机构" placeholder="请选择机构" type="text"
					displayable="false" rightIconType="right" @iconClick="commonSelectOpen('store')" required />

				<eui-card-input v-model="dataModel.c_property_type"
					:range="getOtherStorageSelectList('物业服务类型', taskType)" title="所属类型" rightIconType="right"
					type="selector" placeholder="请选择所属类型" alignType="right" required />

				<eui-card-input v-model="dataModel.c_urgent" :range="getDictSelectList('物业服务申请紧急程度')" title="紧急程度"
					rightIconType="right" type="selector" placeholder="请选择紧急程度" alignType="right" required />

				<eui-card-input v-model="dataModel.c_provider_name" title="商户" placeholder="请选择商户" type="text"
					displayable="false" rightIconType="right" @iconClick="selectOpen('partner')" />

				<eui-card-input v-model="dataModel.c_counter_name" title="铺位" placeholder="请选择铺位" type="text"
					displayable="false" rightIconType="right" @iconClick="selectOpen('counter')" />

				<eui-card-input v-model="dataModel.c_con_no" title="合同号" placeholder="请选择合同号" type="text"
					displayable="false" rightIconType="right" @iconClick="selectOpen('contract')" />

				<eui-card-input v-model="dataModel.c_req_src" :range="getDictSelectList('物业服务申请来源')" title="申请来源"
					rightIconType="right" type="selector" placeholder="请选择申请来源" alignType="right" />

				<eui-card-input v-model="dataModel.c_req_user" title="申请人" placeholder="请录入申请人" type="text"
					alignType="right" maxlength="20" />

				<eui-card-input v-model="dataModel.c_req_phone" title="联系电话" type="text" placeholder="请录入联系电话"
					maxlength="12" alignType="right" />

				<eui-card-input v-model="dataModel.c_req_dt" title="申请时间" placeholder="请输入申请时间" type="date"
					alignType="right" />

				<eui-card-input v-model="dataModel.c_question" title="详情" placeholder="请输入详情内容" type="textarea"
					maxlength="200" required />
			</eui-base-card>

			<eui-base-card title="申请内容" v-show="dataItems.length > 0">
				<eui-card-input v-for="(item, index) in dataItems" :key="index" v-model="item.c_value"
					:placeholder="item.c_placeholder" :range="item?.c_option_list" :title="item?.c_title" maxlength="50"
					:type="item.c_input_type" :required="item.c_required == '1'" />
			</eui-base-card>
			<eui-base-card title='图片上传'>
				<UploadFile :autoUpload="false" fileMediatype="image" :fileId="dataModel.c_id" fileClass="物业服务申请单"
					return-type="array" mode="grid" :fileMap="createAddId(dataModel)"></UploadFile>
			</eui-base-card>
		</eui-page-content>
		<template #bottom>
			<view class="bt-button">
				<eui-button type="primary" title="提交" @click="submit" />
			</view>
		</template>
	</eui-page-frame>
</template>

<script setup lang="ts">
import { onMounted, ref, watch } from 'vue'
import UploadFile from '@/components/UploadFile.vue';
import { useMainStore } from "@/store/modules/store";
import useSaveBill from '@/hooks/useSaveBill';
import { getRelatedName, getOtherStorageSelectList, getDictSelectList, getStoreRelatedName } from '../components/RelatedName.js';
import useService from '@/hooks/useService';
import service from '../../../common/service.js';
import Enjoy from '../../../common/enjoy';
import { formatNow } from '../../../hooks/useUtils.js';
import type { propertyTaskMain, PropertyTaskDetail } from '../types/propertyTypes/property.d.ts';

const apiService = useService({ prefix: "apiApi" });
const mainStore = useMainStore();
const { loginInfo } = mainStore;
const title = ref('新增维修派工单');
const taskType = '0002';

const uniqueKey = '管易通物业模块服务';

const { save, createId } = useSaveBill({
	prefix: 'apiApi',
	table: {
		main: [
			{
				tableName: "tb_mo_property_task",
				primaryKeys: ["c_tenant_id", "c_id"],
			},
		],
		detail: [
			{ tableName: 'tb_mo_property_task_g', primaryKeys: ['c_tenant_id', 'c_id', 'c_sort'] },
			{ tableName: 'tb_mo_property_task_fee', primaryKeys: ['c_tenant_id', 'c_id', 'c_sort'] }
		]
	},
	uniqueKey: uniqueKey,
	method: "EnjoyBillSave",
	billName: '维修派工单',
	billType: 'DA1'
});

const serviceItems = ref([])

const dataItems = ref([])


const mapEditStyle = (type: string) => {
	switch (type) {
		case "0":
			return 'radio';
		case "1":
			return 'multi';
		case "2":
			return 'text';
		case "3":
			return 'date';
		case "4":
			return 'number2';
		// case "5":
		// 	return 'textarea';
		// case "6":
		// 	return 'selector';
		default:
			return 'text';
	}
};

// 监听键盘高度变化事件或者是展开/收起事件（此能力由原生native支持）
// uni.onKeyboardHeightChange(res => {
// 	console.log(res.height)
// 	if (res.height > 0) {
// 		setTimeout(() => {
// 			// uniapp 支持的
// 			uni.pageScrollTo({
// 				scrollTop: 200,
// 				duration: 50,
// 			})
// 		}, 100)
// 	}
// })

const dataModel = ref(
	{
		c_tenant_id: '',//租户编码
		c_id: '',//单号
		c_bill_type: 'DA1',  //单据类型(tb_sc_bill_type中定义)
		c_status: '0',   //单据状态(0-尚未审核,3-已审核,5-已生效,9-已作废)(tb_id_sys定义:s_gl_bill_status) 
		c_adno: '',      //部门编码
		c_adname: '',
		c_store_id: loginInfo.sUserStore,  //机构编码
		c_store_name: '[' + loginInfo.sUserStore + ']' + loginInfo.sUserStoreName,  //机构名称
		c_property_type: '',   //物业服务类型
		c_urgent: '',//紧急程度
		c_provider: '',//供应商
		c_provider_name: '',//供应商名称
		c_counter_no: '',//铺位编码
		c_counter_name: '',//铺位名称
		c_con_no: '',//合同编码
		c_req_src: '',//申请来源
		c_req_user: '',//申请人
		c_req_phone: '',//申请人电话
		c_req_dt: formatNow('YYYY-MM-DD HH:mm:ss'),//申请时间
		c_question: '',//申请详情

		c_src_id: '',
		c_src_type: '',
		c_mk_store_id: loginInfo.sUserStore,
		c_mk_dt: formatNow('YYYY-MM-DD HH:mm:ss'),
		c_mk_userno: loginInfo.sUser,
		c_approve_status: '1',
		c_approve_dt: null,
		c_mk_type: '0',
		c_au_dt: null,
		c_au_userno: '',
		c_print_userno: '',
		c_print_dt: null,
		c_print_count: 0,
		c_note: '',
		c_sys_note: '',
	},
);

const isAdd = ref(true);

const createAddId = async (dataModel: propertyTaskMain) => {
	if (!dataModel.c_id) {
		await createId(dataModel)
		isAdd.value = true
	}
}

onMounted(async () => {
	console.log('onMounted')
	serviceItems.value = service.getLocalStorage('rdsPServiceItem');
	console.log('物业服务项目22', serviceItems.value)
})

watch(() => dataModel.value.c_property_type, async (newValue, oldValue) => {
	console.log('watchnewValue', newValue)
	if (newValue) {
		console.log('dataItems', dataItems.value)

		dataItems.value = serviceItems.value?.filter(t => t.c_type == newValue).map(
			item => {
				return {
					...item,
					c_option_list: item.c_options ? JSON.parse(item.c_options).map(x => { return { text: x.title, value: x.value, checked: item.c_default_value.includes(x.value) } }) : '',
					c_value: item.c_default_value || '',
					c_placeholder: '请输入' + item.c_title,
					c_input_type: mapEditStyle(item.c_edit_style)
				};
			}
		);
		console.log('dataItems.value', dataItems.value)
	}
})

const SelectionChanged = (type, item) => {
	switch (type) {
		case 'partner':
			dataModel.value.c_provider = item.value;
			dataModel.value.c_provider_name = '[' + item.value + ']' + item.text;
			break;
		case 'counter':
			dataModel.value.c_counter_no = item.value;
			dataModel.value.c_counter_name = item.text;
			break;
		case 'contract':
			dataModel.value.c_con_no = item.value;
			break;
	}
}

const selectOpen = (selectType: string) => {
	let url = `../modals/index?type=${selectType}`;
	//先选择机才能选铺位
	if(selectType==='counter'){
		if(!dataModel.value.c_store_id){
			uni.showToast({
				title: '请先选择机',
				icon: 'none'
			});
			return;
		}
		url = `../modals/index?type=${selectType}&storeId=${dataModel.value.c_store_id}`;
	}
	//如果选择合同时已经有商户编码，则带着商户编码查询合同
	if(selectType==='contract' && dataModel.value.c_provider){
		url = `../modals/index?type=${selectType}&partnerNo=${dataModel.value.c_provider}`;
	}

	uni.navigateTo({
		url: url
	});
}

const CommonSelectionChanged = (e) => {
	switch (e.SelectionType) {
		case '机构选择':
			dataModel.value.c_store_id = e.BackParms.Key;
			dataModel.value.c_store_name = '[' + e.BackParms.Key + ']' + (e.BackParms.Value ? e.BackParms.Value : '');
			break;
	}
}

const commonSelectOpen = (item: string) => {
	let parms = Enjoy.GetDialogParms();
	parms.CallBack = CommonSelectionChanged;
	switch (item) {
		case 'store':
			parms.SelectionType = "机构选择";
			parms.SelectedItems = dataModel.value.c_store_id;
			break;
	}
	Enjoy.OpenDialog(parms)
}

const submit = async () => {
	if (!dataModel.value.c_store_id) {
		uni.showToast({
			duration: 2000,
			icon: 'none',
			title: '请选择机构',
			mask: true,
		});
		return;
	}
	if (!dataModel.value.c_property_type) {
		uni.showToast({
			duration: 2000,
			icon: 'none',
			title: '请选择所属类型',
			mask: true,
		});
		return;
	}
	if (!dataModel.value.c_urgent) {
		uni.showToast({
			duration: 2000,
			icon: 'none',
			title: '请选择紧急程度',
			mask: true,
		});
		return;
	}
	if (!dataModel.value.c_question) {
		uni.showToast({
			duration: 2000,
			icon: 'none',
			title: '请录入详情',
			mask: true,
		});
		return;
	}
	console.log('submitdataItems', dataItems.value)
	if (dataItems.value.find(x => !x.c_value && x.c_required == '1')) {
		var empty = dataItems.value.find(x => !x.c_value && x.c_required == '1');
		uni.showToast({
			duration: 2000,
			icon: 'none',
			title: '请录入申请内容' + empty?.c_title,
			mask: true,
		});
		return;
	}

	uni.showLoading({ title: "正在保存...", mask: true })
	const toSaveMainData: propertyTaskMain =
	{
		...dataModel.value,
	}

	let sort = 1;
	const toSaveDeailData: PropertyTaskDetail[] = dataItems.value.map(
		item => {
			return {
				c_tenant_id: "",
				c_id: dataModel.value.c_id,
				c_sort: sort++,
				c_service_id: item.c_id,
				c_value: item.c_value,
				c_options:item.c_options,
				c_title: item.c_title,
				c_class: item.c_class,
				c_edit_style: item.c_edit_style,
				c_required: item.c_required,
				c_note: ''
			} as PropertyTaskDetail;
		})

	let details = [{
		NewList: isAdd.value ? toSaveDeailData : [],
		ModifiedList: isAdd.value ? [] : toSaveDeailData,
		DelList: []
	}];

	console.log('toSave', dataModel.value, toSaveMainData, details)
	const result = await save(isAdd.value, toSaveMainData, details);
	uni.hideLoading();
	if (result) {
		uni.showToast({
			duration: 2000,
			icon: 'none',
			title: '提交成功',
			mask: true,
		});
		uni.navigateBack();
	}
}
//获取单据详情
const getBillData = async (id: string) => {
	uni.showLoading({ title: "查询中...", mask: true });
	const res = await apiService.request(uniqueKey, 'ServiceRequestQuery', { BillId: id });
	console.log('getBillData', res)
	uni.hideLoading();
	if (res) {
		const resObject = res;
		if (resObject) {
			dataModel.value =
			{
				...resObject.ds[0],
				c_store_name: resObject.ds[0].c_store_id ? '[' + resObject.ds[0].c_store_id + ']' + getStoreRelatedName(resObject.ds[0].c_store_id) : '',
				c_provider_name: resObject.ds[0].c_provider ? '[' + resObject.ds[0].c_provider + ']' + getRelatedName('rdsProviders', resObject.ds[0].c_provider) : '',
			};
		}
	}
}

const validateMain = async (t: string, e: any) => {
	console.log('validateMain', t, e);
	console.log('serviceItems', serviceItems.value);
	switch (t) {
		case 'c_proprty_type':
			if (!e) {
				uni.showToast({
					duration: 3500,
					icon: 'none',
					title: '所属类型不能为空'
				});
				return;
			}
			else {
				dataItems.value = serviceItems.value?.filter(t => t.c_type == e).map(
					item => {
						return {
							...item,
							c_options:JSON.parse(item.c_options),
							c_option_list: JSON.parse(item.c_options).map(x => { return { text: x.label, value: x.value, checked: false } }),
							c_selected: item.c_default_value || '',
						};
					}
				);
			}

			console.log('dataItems', dataItems.value);
			break;
		case 'c_discount':

			break;
	}
}

defineExpose({
	SelectionChanged
})
</script>

<style lang="scss">

.navigation {
	background-color: #FFFFFF;
	flex: 0 0 auto;
	margin-bottom: 5px;
}

.bt-button {
	background-color: white;
	padding: 20rpx;
	height: 80rpx;
	width: 96%;
	bottom: 20rpx;
	right: 0rpx;
	position: fixed;
	margin-bottom: -20rpx;
	display: flex;
	justify-content: space-between;
}

::v-deep.e-card:first-of-type .e-card__header {
    margin-left: 24rpx ;
}

</style>